package com.stu.day18;

import java.lang.annotation.*;
import java.lang.reflect.Method;

/**
 * @author zy
 * @date 2025/2/20 15:54
 */
@Inherited // 父类类上的注解可以被子类继承
@Retention(RetentionPolicy.RUNTIME)//表示在运行期间可以通过反射的技术获取到这个注解
@Target(value= {ElementType.METHOD,ElementType.TYPE})
public @interface MyAnno {
    //定义一个属性,并且使用默认的名称value
    //String value();
    String value1();

    //允许定义多个属性的
    int value2();
}

//如果注解的属性名称使用value的话,那么value这个单词可以省略不写
@MyAnno(value1="admin",value2 = 30)
class MyAnnoDemo{

    @MyAnno(value1="tom",value2 = 18)
    public void test01(){
    }

    public static void main(String[] args) throws NoSuchMethodException {
        //1. 获取Class实例
        Class<?> c = MyAnnoDemo.class;
        //a. 获取Method实例

        if(c.isAnnotationPresent(MyAnno.class)){
            //1. 通过反射获取注解对象
            MyAnno myAnno = c.getDeclaredAnnotation(MyAnno.class);
            //获取注解的属性信息
            String value1 = myAnno.value1();
            int value2 = myAnno.value2();
            System.out.println(value1+":"+value2);
        }
        //2. 判断这个类上面是否加了注解MyAnno
        Method m = c.getDeclaredMethod("test01");
        //判断这个方法上是否加了注解
        if(m.isAnnotationPresent(MyAnno.class)){
            //1. 通过反射获取注解对象
            MyAnno myAnno = m.getDeclaredAnnotation(MyAnno.class);
            //获取注解的属性信息
            String value1 = myAnno.value1();
            int value2 = myAnno.value2();
            System.out.println(value1+":"+value2);
        }
    }
}
class MyAnnoSub extends MyAnnoDemo{

    //父类方法的注解是不被继承的
    @Override
    public void test01() {

    }
    public static void main(String[] args) {
        Class<?> c = MyAnnoSub.class;
        System.out.println(c.isAnnotationPresent(MyAnno.class));
    }
}
